import CalendarDay from "../calendarDay/calendarDay";
import SignInTimeLess from "./signInTime.module.less";
import {
  QuestionCircleOutlined,
  CaretRightOutlined,
  CaretLeftOutlined,
} from "@ant-design/icons";
import { Calendar, theme, Select, Typography, message, Modal } from "antd";
import type { CalendarProps } from "antd";
import dayjs from "dayjs";
import type { Dayjs } from "dayjs";
import "dayjs/locale/zh-cn";
import dayLocaleData from "dayjs/plugin/localeData";
import {
  GetUserSignInDateListApi,
  GetUserSignInToDayApi,
  SignInByUserIdApi,
  BuSignInApi,
} from "@/http/api/signIn";
import { GetUserSignInfoApi } from "@/http/api/user";

import { useEffect, useState } from "react";
dayjs.extend(dayLocaleData);
function SignInTime() {
  const [DateList, setDateList] = useState([]);
  const [signInFlag, setSignInFlag] = useState(false);
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [BuCardNum, setBuCardNum] = useState(0);
  const [KeepSignDay, setKeepSignDay] = useState(0);
  const [AddSignDay, setAddSignDay] = useState(0);
  const [OreNum, setOreNum] = useState(0);
  useEffect(() => {
    GetUserSignInDateList();
    GetDateSignInStatus();
    GetUserSignInfo();
  }, []);
  const GetUserSignInDateList = async () => {
    const res: any = await GetUserSignInDateListApi();
    console.log("获取到签到列表", res);
    if (res.status === 0) {
      setDateList(() => res.DateList);
    }
  };

  const GetUserSignInfo = async () => {
    const res: any = await GetUserSignInfoApi();
    console.log("获取到用户基础信息", res);
    if (res.status === 0) {
      setBuCardNum(res.UserSignInfo.BuCardNum);
      setKeepSignDay(res.UserSignInfo.KeepSignDay);
      setAddSignDay(res.UserSignInfo.AddSignDay);
      setOreNum(res.UserSignInfo.OreNum);
    }
  };

  const GetDateSignInStatus = async () => {
    const params = {
      Date: dayjs().format("YYYY-MM-DD"),
    };
    const res: any = await GetUserSignInToDayApi(params);
    console.log("签到状态", res);
    if (res.status === 0) {
      setSignInFlag(!res.Yes);
    }
  };

  const SignIn = async () => {
    const params = {
      Date: dayjs().format("YYYY-MM-DD"),
    };
    const res: any = await SignInByUserIdApi(params);
    console.log("签到结果", res);
    if (res.status === 0) {
      message.success("签到成功");
      GetDateSignInStatus();
      GetUserSignInDateList();
      GetUserSignInfo();
    }
  };

  const onpanelSelect = (date: any) => {
    console.log("触发了选择时间");
    let targetDateStr = dayjs(date);
    let now = dayjs();
    let diffDays = now.diff(targetDateStr, "day");
    console.log("点击结果", date, dayjs(date).format("YYYY-MM-DD"));
    if (dayjs(date).isBefore(dayjs().format("YYYY-MM-DD"))) {
      if (diffDays <= 30 && diffDays >= 0) {
        console.log(`${targetDateStr} 是在当前时间的前三十天之中`);
        BuSignInMethods(dayjs(date).format("YYYY-MM-DD"));
      } else {
        console.log(`${targetDateStr} 不在当前时间的前三十天之中`);
        message.error("历史日期已经超过三十天，不能补签");
      }
    }
  };

  const BuSignInMethods = async (data: String) => {
    const params = {
      Date: data,
    };
    const res: any = await BuSignInApi(params);
    console.log("补签结果", res);
    if (res.status === 0) {
      if (!res.NoCardId) {
        message.success("补签成功");
        GetUserSignInfo();
      } else {
        setIsModalOpen(true);
      }
    }
  };

  const onPanelChange = (value: Dayjs, mode: CalendarProps<Dayjs>["mode"]) => {
    console.log(value.format("YYYY-MM-DD"), mode);
  };
  const dateCellRender = (value: Dayjs) => {
    const Flag = checkSignInDate(dayjs(value).format("YYYY-MM-DD"));
    return Flag ? (
      <div className="notes-month">
        <span className="icon iconfont icon-kuangshi1"></span>
        +100
      </div>
    ) : dayjs().format("YYYY-MM-DD") === dayjs(value).format("YYYY-MM-DD") ? (
      <div className="today">今日</div>
    ) : dayjs(value).isBefore(dayjs().format("YYYY-MM-DD")) ? (
      <div className="retrospective">待补签</div>
    ) : (
      <div className="num">
        <span className="icon iconfont icon-kuangshi1"></span>
        +100
      </div>
    );
  };
  const checkSignInDate = (date: string) => {
    return DateList.some((item: any) => {
      return date === item.SignInDate;
    });
  };

  const handleOk = () => {
    setIsModalOpen(false);
  };

  const handleCancel = () => {
    setIsModalOpen(false);
  };
  return (
    <>
      <div className={SignInTimeLess.signInTime_content}>
        <div className="top_title">
          <div className="left">每日签到</div>
          <div className="right">
            <QuestionCircleOutlined />
            <span>签到规则</span>
          </div>
        </div>
        <div className="content">
          <div className="content_info_num">
            <div className="left_info">
              <div className="item_info">
                <div className="top_num blur">{KeepSignDay}</div>
                <div className="bottom_name">连续签到天数</div>
              </div>
              <div className="item_info">
                <div className="top_num">{AddSignDay}</div>
                <div className="bottom_name">累计签到天数</div>
              </div>
              <div className="item_info">
                <div className="top_num">{OreNum}</div>
                <div className="bottom_name">当前矿石数</div>
              </div>
            </div>
            <div className="right_btn">
              {signInFlag ? (
                <div className="signBtn" onClick={SignIn}>
                  <img src="/public/fontimg/zuanshi.png" alt="" />
                  <div>立即签到</div>
                </div>
              ) : (
                <div className="haveSignIn">
                  <div>今日已签到</div>
                </div>
              )}
            </div>
          </div>
          <div className="calender">
            <div className="left_calendar">
              <Calendar
                fullscreen={false}
                onSelect={(date, { source }) => onpanelSelect(date, source)}
                cellRender={dateCellRender}
                headerRender={({ value, type, onChange, onTypeChange }) => {
                  let currentDate = dayjs();
                  let lastMonth = currentDate.subtract(1, "month");
                  let currentYear = dayjs().year();
                  let currentMonth = dayjs().month();
                  // 获取年份和月份
                  let lastYear = lastMonth.year();
                  let lastMonthNumber = lastMonth.month(); // month() 返回的是0-based，所以要加1

                  /*    let current = value.clone();
                  const localeData = value.localeData();
                  const months = []; */

                  let year = value.year();
                  let month = value.month() + 1;
                  console.log("value", value);
                  const leftSelectTime = () => {
                    onChange(value.clone().year(lastYear));
                    onChange(value.clone().month(lastMonthNumber));
                  };

                  const RightSelectTime = () => {
                    onChange(value.clone().year(currentYear));
                    onChange(value.clone().month(currentMonth));
                  };
                  return (
                    <div style={{ padding: 8 }}>
                      <div className="calendar_header">
                        <div className="left_time_select">
                          <div
                            className={[
                              year !== currentYear || month !== currentMonth + 1
                                ? "NoClick"
                                : "",
                              "left_icon",
                            ].join(" ")}
                            onClick={leftSelectTime}
                          >
                            <CaretLeftOutlined />
                          </div>
                          <div className="center_info">
                            <div className="year">{year}</div>
                            <div>年</div>
                            <div className="month">{month}</div>
                            <div>月</div>
                          </div>
                          <div
                            className={[
                              year === currentYear && month === currentMonth + 1
                                ? "NoClick"
                                : "",
                              "right_icon",
                            ].join(" ")}
                            onClick={RightSelectTime}
                          >
                            <CaretRightOutlined />
                          </div>
                        </div>
                        <div className="right_Supplementar_signature_num">
                          <div className="icon">
                            <img src="/public/img/bu.avis" alt="" />
                          </div>
                          补签卡：<span>{BuCardNum}</span>张
                        </div>
                      </div>
                    </div>
                  );
                }}
                onPanelChange={onPanelChange}
              />
            </div>
            <div className="right_ok_doth">
              <CalendarDay DateString={dayjs().format("YYYY-MM-DD")} />
            </div>
          </div>
        </div>
        {/* 补签提醒内容 */}
        <Modal
          open={isModalOpen}
          onOk={handleOk}
          onCancel={handleCancel}
          footer={null}
          centered
          wrapClassName={"bu_modal"}
          getContainer={false}
        >
          <div className="modal_content_all">
            <div className="modal_title">补签卡不足</div>
            <div className="modal_tips">
              当前补签卡不足，去&nbsp;<a>福利兑换-社区道具</a>&nbsp;
              兑换补签卡后再来补签吧。
            </div>
            <div className="modal_btn">
              <div className="left_btn">暂不兑换</div>
              <div className="right_btn">立即兑换</div>
            </div>
          </div>
          <div className="icon_bu">
            <img src="/public/img/bu_big.avis" alt="" />
          </div>
        </Modal>
      </div>
    </>
  );
}

export default SignInTime;
